package net.bblbs.zhongrx;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.design.widget.FloatingActionButton;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import android.support.v4.app.Fragment;

import net.bblbs.zhongrx.db.Person;
import net.bblbs.zhongrx.service.UploadService;
import net.bblbs.zhongrx.util.AttachEnum;
import net.bblbs.zhongrx.util.JsonUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * An activity representing a list of Sections. This activity
 * has different presentations for handset and tablet-size devices. On
 * handsets, the activity presents a list of items, which when touched,
 * lead to a {@link SectionDetailActivity} representing
 * item description. On tablets, the activity presents the list of items and
 * item description side-by-side using two vertical panes.
 */
public class SectionListActivity extends BaseActivity implements View.OnClickListener{

    private static final String TAG = "ZRX_SectionListActivity";
    /**
     * Whether or not the activity is in two-pane mode, i.e. running on a tablet
     * device.
     */
    private boolean mTwoPane;

//    public static ApplicationData data = new ApplicationData();
    public static Person person ;

    private UploadService.UploadBinder uploadBinder;

    private ServiceConnection connection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            uploadBinder = (UploadService.UploadBinder) service;
        }

    };

    public String[] attachFiles = new String[AttachEnum.values().length];
    public String[] filenames = new String[AttachEnum.values().length];
//    public boolean[] needUpload = new boolean[AttachEnum.values().length];

    public ArrayList<String> mImgList1 = new ArrayList<String>();
    public ArrayList<String> mImgList2 = new ArrayList<String>();
    public ArrayList<String> mImgList3 = new ArrayList<String>();
    public ArrayList<String> mImgList4 = new ArrayList<String>();
    public ArrayList<String> mDynImgList = new ArrayList<String>();

    String[] mFrag1NameArray;
    String[] mFrag2NameArray;
    String[] mFrag3NameArray;
    String[] mFrag4NameArray;
    String[] mDynNameArray;

    public boolean additionalDataChanged = false;

    public String submitList="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_section_list);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setTitle(getTitle());

        List<SectionContent.SectionItem> list = SectionContent.ITEMS;
        Intent intents = getIntent();
        Bundle extra=intents.getExtras();

        person = (Person) getIntent().getParcelableExtra("person_data");


        Log.d(TAG, "person from select activity: "+ person.toString());

//        previousID_CARD_1_F = getIntent().getStringExtra(AttachEnum.ID_CARD_1_F.getValue());
//        previousID_CARD_1_B = getIntent().getStringExtra(AttachEnum.ID_CARD_1_B.getValue());

        int i =0;
        for(AttachEnum attach : AttachEnum.values()){
            attachFiles[i] = getIntent().getStringExtra(attach.getValue());
            filenames[i] = attach.getValue();
            i++;
        }

        String fgmt1Imgs = getIntent().getStringExtra(Photo1Fragment.SP_NAME);
        String[] fgmt1ImgArr = fgmt1Imgs.split("\\|", -1);
        mImgList1 = new ArrayList<String>(Arrays.asList(fgmt1ImgArr));

        String fgmt2Imgs = getIntent().getStringExtra(Photo2Fragment.SP_NAME);
        String[] fgmt2ImgArr = fgmt2Imgs.split("\\|", -1);
        mImgList2 = new ArrayList<String>(Arrays.asList(fgmt2ImgArr));

        String fgmt3Imgs = getIntent().getStringExtra(Photo3Fragment.SP_NAME);
        String[] fgmt3ImgArr = fgmt3Imgs.split("\\|", -1);
        mImgList3 = new ArrayList<String>(Arrays.asList(fgmt3ImgArr));

        String fgmt4Imgs = getIntent().getStringExtra(Photo4Fragment.SP_NAME);
        String[] fgmt4ImgArr = fgmt4Imgs.split("\\|", -1);
        mImgList4 = new ArrayList<String>(Arrays.asList(fgmt4ImgArr));

        String dynImgs = getIntent().getStringExtra(DynamicPhotoFragment.SP_NAME);
        String[] dynImgArr = dynImgs.split("\\|", -1);
        mDynImgList = new ArrayList<String>(Arrays.asList(dynImgArr));

        additionalDataChanged= false;
        submitList = "";

        SharedPreferences pref = this.getSharedPreferences("dynamic_info", Context.MODE_PRIVATE);
        String additionalData = pref.getString("dynamic_info_"+ person.getId(),"");

        if(TextUtils.isEmpty(additionalData)){
            pref.edit().putString("dynamic_info_"+ person.getId(), person.getAdditionalData()).apply();
        }


        Intent intent = new Intent(this, UploadService.class);
        startService(intent); // 启动服务
        boolean result = bindService(intent, connection, BIND_AUTO_CREATE); // 绑定服务

        View recyclerView = findViewById(R.id.section_list);
        assert recyclerView != null;
        setupRecyclerView((RecyclerView) recyclerView);

        if (findViewById(R.id.section_detail_container) != null) {
            // The detail container view will be present only in the
            // large-screen layouts (res/values-w900dp).
            // If this view is present, then the
            // activity should be in two-pane mode.
            mTwoPane = true;
        }
    }

    @Override
    public void onClick(View v) {

    }

    public boolean canUpload(){
        boolean result = false;
        SharedPreferences pref = this.getSharedPreferences("dynamic_info", Context.MODE_PRIVATE);

        if (JsonUtil.isChanged(pref.getString("dynamic_info_" + person.getId(),""), person.getAdditionalData())){
            additionalDataChanged = true;
            submitList  += "补充资料\n";
            result = true;
        }


        for(int i = 0 ; i < attachFiles.length; i++ ){
            if (!TextUtils.isEmpty(attachFiles[i])){
                submitList  += filenames[i]+"\n";
                result = true;
            }
        }

        SharedPreferences pref1 = this.getSharedPreferences(Photo1Fragment.SP_NAME, Context.MODE_PRIVATE);
        String frag1Names = pref1.getString(Photo1Fragment.SP_NAME + "_"+ person.getId(),"");
        mFrag1NameArray = frag1Names.split("\\|", -1);

        for(int i = 0 ; i < mImgList1.size() ; i++){
            if(!TextUtils.isEmpty(mImgList1.get(i))){
                submitList  += mFrag1NameArray[i]+"\n";
                result = true;
            }
        }

        SharedPreferences pref2 = this.getSharedPreferences(Photo2Fragment.SP_NAME, Context.MODE_PRIVATE);
        String frag2Names = pref2.getString(Photo2Fragment.SP_NAME + "_"+ person.getId(),"");
        mFrag2NameArray= frag2Names.split("\\|", -1);

        for(int i = 0 ; i < mImgList2.size() ; i++){
            if(!TextUtils.isEmpty(mImgList2.get(i))){
                submitList  += mFrag2NameArray[i]+"\n";
                result = true;
            }
        }

        SharedPreferences pref3 = this.getSharedPreferences(Photo3Fragment.SP_NAME, Context.MODE_PRIVATE);
        String frag3Names = pref3.getString(Photo3Fragment.SP_NAME + "_"+ person.getId(),"");
        mFrag3NameArray = frag3Names.split("\\|", -1);

        for(int i = 0 ; i < mImgList3.size() ; i++){
            if(!TextUtils.isEmpty(mImgList3.get(i))){
                submitList  += mFrag3NameArray[i]+"\n";
                result = true;
            }
        }

        SharedPreferences pref4 = this.getSharedPreferences(Photo4Fragment.SP_NAME, Context.MODE_PRIVATE);
        String frag4Names = pref4.getString(Photo4Fragment.SP_NAME + "_"+ person.getId(),"");
        mFrag4NameArray = frag4Names.split("\\|", -1);

        for(int i = 0 ; i < mImgList4.size() ; i++){
            if(!TextUtils.isEmpty(mImgList4.get(i))){
                submitList  += mFrag4NameArray[i]+"\n";
                result = true;
            }
        }

        SharedPreferences pref5 = this.getSharedPreferences(DynamicPhotoFragment.SP_NAME, Context.MODE_PRIVATE);
        String dynNames = pref5.getString(DynamicPhotoFragment.SP_NAME + "_" + person.getId(),"");
        mDynNameArray = dynNames.split("\\|", -1);

        for(int i = 0 ; i < mDynImgList.size() ; i++){
            if(!TextUtils.isEmpty(mDynImgList.get(i))){
                submitList  += mDynNameArray[i]+"照片\n";
                result = true;
            }
        }




        return result;
    }

    public void upload(){
        List<String> uplaodFileNames = new ArrayList<String>();
        List<String> uploadFileURLs= new ArrayList<String>();

        for(int i = 0 ; i < attachFiles.length; i++ ){
            if (!TextUtils.isEmpty(attachFiles[i])){
                uplaodFileNames.add(filenames[i]);
                uploadFileURLs.add(attachFiles[i]);
            }
        }


        for(int i = 0 ; i < mImgList1.size() ; i++){
            if(!TextUtils.isEmpty(mImgList1.get(i))){
                uplaodFileNames.add(mFrag1NameArray[i]);
                uploadFileURLs.add(mImgList1.get(i));
            }
        }

        for(int i = 0 ; i < mImgList2.size() ; i++){
            if(!TextUtils.isEmpty(mImgList2.get(i))){
                uplaodFileNames.add(mFrag2NameArray[i]);
                uploadFileURLs.add(mImgList2.get(i));
            }
        }

        for(int i = 0 ; i < mImgList3.size() ; i++){
            if(!TextUtils.isEmpty(mImgList3.get(i))){
                uplaodFileNames.add(mFrag3NameArray[i]);
                uploadFileURLs.add(mImgList3.get(i));
            }
        }

        for(int i = 0 ; i < mImgList4.size() ; i++){
            if(!TextUtils.isEmpty(mImgList4.get(i))){
                uplaodFileNames.add(mFrag4NameArray[i]);
                uploadFileURLs.add(mImgList4.get(i));
            }
        }

        for(int i = 0 ; i < mDynImgList.size() ; i++){
            if(!TextUtils.isEmpty(mDynImgList.get(i))){
                uplaodFileNames.add(mDynNameArray[i]+"照片");
                uploadFileURLs.add(mDynImgList.get(i));
            }
        }

//        if (uploadFileURLs.size() ==0) return;
//                String[] params = new String[uploadFileURLs.size()];
//
//                for(int i = 0; i < uploadFileURLs.size(); i++){
//                    params[i] = filenames[i]+ ":" + attachFiles[i];
//                }

        uploadBinder.startUpload(uplaodFileNames, uploadFileURLs, person.getId(), this);
    }

    private void setupRecyclerView(@NonNull RecyclerView recyclerView) {
        recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter((SectionContent.ITEMS)));
    }

    public class SimpleItemRecyclerViewAdapter
            extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {

        private final List<SectionContent.SectionItem> mValues;

        public SimpleItemRecyclerViewAdapter(List<SectionContent.SectionItem> items) {
            mValues = items;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.section_list_content, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(final ViewHolder holder, final int posIdx) {  // !!! position = posIdx + 1 !!!

            final int position = posIdx+1; // !!! position = posIdx + 1 !!!

            //holder.mItem = mValues.get(posIdx);
            holder.mIdView.setText(mValues.get(posIdx).id);
            holder.mContentView.setText(mValues.get(posIdx).content);

            holder.mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mTwoPane) {

                        //下面几行用Bundle给Fragment传递参数，暂时用不到
                        //Bundle arguments = new Bundle();
                        //arguments.putString(SectionDetailFragment.ARG_ITEM_ID, holder.mItem.id);
                        //SectionDetailFragment fragment = new SectionDetailFragment();
                        //fragment.setArguments(arguments);

                        //加载对应点击条目的Fragment

                        Fragment fragment = SectionContent.getSectionFragmentByPosition(position);// !!! position = posIdx + 1 !!!
                        String tag = SectionContent.getSectionFragmentTag(position);
                        FragmentManager fm = getSupportFragmentManager();
                        FragmentTransaction ft = fm.beginTransaction();
                        ft.setAllowOptimization(false)
                                .replace(R.id.section_detail_container, fragment,tag)
                                .commit();

                        fm.executePendingTransactions();
                    } else {
                        Context context = v.getContext();
                        Intent intent = new Intent(context, SectionDetailActivity.class);
                        // intent.putExtra(SectionDetailFragment.ARG_ITEM_ID, holder.mItem.id);
                        intent.putExtra(SectionContent.KEY_FRAGMENT, position);

                        context.startActivity(intent);

                    }
                }
            });
        }

        @Override
        public int getItemCount() {
            return mValues.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            public final View mView;
            public final TextView mIdView;
            public final TextView mContentView;
            //public SectionContent.SectionItem mItem;

            public ViewHolder(View view) {
                super(view);
                mView = view;
                mIdView = (TextView) view.findViewById(R.id.id);
                mContentView = (TextView) view.findViewById(R.id.content);
            }

            @Override
            public String toString() {
                return super.toString() + " '" + mContentView.getText() + "'";
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(connection);
    }
}
